package com.hoyue.servlet;

import java.io.*;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hoyue.bean.Character;
import com.hoyue.service.CharacterService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

@WebServlet("/CharacterServlet")
public class CharacterServlet extends HttpServlet {

    CharacterService characterService = new CharacterService();
/*
 *  对本servlet进行了复用
 *  @param type servlet接受参数类型flag
 *  -1 读取信息
 *  update 修改信息
 *  insert 新增信息
 */

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String type = request.getParameter("type");
        if(type == null){
            System.out.println("NPE");
            type = -1+"";
        }
        if(type.equals("-1")){
            double randomNum = Math.random();
            request.setAttribute("randomNum", randomNum);
            List<Character> characters = characterService.getAllChar();
            request.setAttribute("characters", characters);
            request.getRequestDispatcher("/WEB-INF/admin/member.jsp").forward(request, response);
        }
        else if (type.equals("update")){
            System.out.println("-----------------------分割线---------------------");
//            String picture_address = request.getParameter("picture_address");
            Character character = new Character();
            String picture_address = request.getParameter("picture_address");

            System.out.println("||||||||||||   " + picture_address);
            Map<String, Object> map = new HashMap<>();
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload sfu = new ServletFileUpload(factory);
            try {
                List<FileItem> items = sfu.parseRequest(request);
                for (FileItem item : items) {
                    if (item.isFormField()) {
                        String fileName = item.getFieldName();
                        String fileValue = item.getString("UTF-8");
                        if (fileName.equals("dateId")){
                            character = characterService.getCharacterById(fileValue);
                        }
                        System.out.println("找到"+fileName+fileValue);
                        map.put(fileName, fileValue);
                    } else {
//                        String picture_address = character.getPicture_address();
                        String name = picture_address.substring(picture_address.lastIndexOf("/") + 1);
                        System.out.println(name);
                        if(item.getName().equals("")) {
                            map.put("picture_address", picture_address);
                            continue;
                        }

                        String photoFolder = request.getServletContext().getRealPath("page/images/character");

                        InputStream inputStream = item.getInputStream();
                        OutputStream outputStream = new FileOutputStream(photoFolder + "/" + name);
                        IOUtils.copy(inputStream, outputStream);

                        inputStream.close();
                        outputStream.close();
                        item.delete();

                        map.put("picture_address", picture_address);
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            }

            try {
                BeanUtils.populate(character, map);
            } catch (Exception e) {
                e.printStackTrace();
            }
            characterService.updateChar(character);
            response.sendRedirect("/CharacterServlet?type=-1");
        }
        else if (type.equals("insert")){
            Character character = new Character();
//            character.setNumber(Integer.parseInt(request.getParameter("number")));
//            character.setName(request.getParameter("name"));
//            character.setPicture_address(request.getParameter("picture_address"));
//            character.setSlogan(request.getParameter("slogan"));
//            CharacterService characterService = new CharacterService();
            Map<String, Object> map = new HashMap<>();
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload sfu = new ServletFileUpload(factory);
            try {
                List<FileItem> items = sfu.parseRequest(request);
                for (FileItem item : items) {
                    if (item.isFormField()) {
                        String fileName = item.getFieldName();
                        String fileValue = item.getString("UTF-8");
                        System.out.println(fileName + "------" + fileValue);
                        map.put(fileName, fileValue);
                    }
                    else {
                        String name = System.currentTimeMillis() + ".jpg";
                        String photoFolder = this.getServletContext().getRealPath("page/images/character");
                        System.out.println(photoFolder);

                        InputStream inputStream = item.getInputStream();
                        OutputStream outputStream = new FileOutputStream(photoFolder + "/" + name);
                        IOUtils.copy(inputStream, outputStream);

                        inputStream.close();
                        outputStream.close();
                        item.delete();

                        map.put("picture_address", "page/images/character/" + name);
                    }
                }

            } catch (FileUploadException e) {
                e.printStackTrace();
            }

            try {
                BeanUtils.populate(character, map);
            } catch (Exception e) {
                e.printStackTrace();
            }
            characterService.addChar(character);
            response.sendRedirect("/CharacterServlet?type=-1");
        }
        else if (type.equals("delete")){
            int id = Integer.parseInt(request.getParameter("id"));
            //查找地址
            String picPath = characterService.getAddressById(id);
            String address = this.getServletContext().getRealPath(picPath);

            File file = new File(address);
            if(file.exists()) {
                file.delete();
            }
            characterService.deleteChar(id);
            response.sendRedirect("/CharacterServlet?type=-1");
        }
    }
    protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
        doPost(request,response);
    }
}